package com.lh.controller;

import com.lh.entity.table.FileProperties;
import com.lh.entity.vo.ConfigEditorPlus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/ueditor")
public class UEditorController {



    @Autowired
    private FileProperties fileProperties;
    /**
     * 处理UEditor的所有请求
     */
    @RequestMapping(value = "/handler", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    public Object handler(HttpServletRequest request,
                          HttpServletResponse response,
                          @RequestParam(value = "file", required = false) MultipartFile file) {

        // 设置CORS头信息
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setHeader("X-Content-Type-Options", "nosniff");

        // 如果是OPTIONS预检请求，直接返回空响应
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return null;
        }

        String action = request.getParameter("action");

        // 处理配置请求
        if ("config".equals(action)) {
            // 特别处理配置请求，确保返回正确的JSON
            response.setContentType("application/json;charset=UTF-8");
            return getConfig();
        }

        // 处理图片上传
        if ("uploadimage".equals(action)) {
            return uploadFile(file, "images");
        }

        // 处理视频上传
        if ("uploadvideo".equals(action)) {
            return uploadFile(file, "videos");
        }

        // 处理文件上传
        if ("uploadfile".equals(action)) {
            return uploadFile(file, "files");
        }

        // 其他未实现的action
        Map<String, Object> result = new HashMap<>();
        result.put("state", "ERROR: 不支持的操作");
        return result;
    }

    public ConfigEditorPlus getConfig() {
        ConfigEditorPlus configEditorPlus = new ConfigEditorPlus();
        return configEditorPlus;
    }


    /**
     * 上传文件处理
     */
    private Map<String, Object> uploadFile(MultipartFile file, String type) {
        Map<String, Object> result = new HashMap<>();

        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            result.put("state", "ERROR: 上传文件为空");
            return result;
        }
        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            // 获取文件扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 生成新的文件名（UUID + 扩展名）
            String fileName = UUID.randomUUID().toString() + extension;

            // 按日期和类型创建存储目录
            String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());

            String basePath = fileProperties.getUploadPath();


            String saveDir = basePath + File.separator + type + File.separator + dateDir;
            File dir = new File(saveDir);
            if (!dir.exists()) {
                dir.mkdirs();  // 创建目录
            }

            // 保存文件
            File dest = new File(saveDir + File.separator + fileName);
            file.transferTo(dest);
            String accessPrefix = fileProperties.getOutPath();

            // 构建文件访问URL
            String fileUrl = accessPrefix + type + "/" + dateDir + "/" + fileName;

            // 上传成功返回结果
            result.put("state", "SUCCESS");  // 必须为SUCCESS
            result.put("url", fileUrl);      // 文件访问URL
            result.put("title", originalFilename);
            result.put("original", originalFilename);
            result.put("type", extension.replace(".", ""));
            result.put("size", file.getSize());

        } catch (IOException e) {
            result.put("state", "ERROR: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }
}